/*************************************************************************
	> File Name: server.cpp
	> Author: 
	> Mail: 
	> Created Time: Thu 24 Sep 2020 03:36:09 PM CST
 ************************************************************************/
#include "define.h"

#define DEFAULT_PORT 12000

int main(int argc, char** argv){
    int listenfd, acceptfd;
    struct sockaddr_in myaddr;
    struct sockaddr_in theiraddr;
    unsigned int sin_size, myport = 12000, lisnum = 10;

    if((listenfd = socket(AF_INET, SOCK_STREAM, 0)) == -1){
        perror("socket: ");
        return -1;
    }
    printf("socket OK!\n");
    myaddr.sin_family = AF_INET;
    myaddr.sin_port = htons(DEFAULT_PORT);
    myaddr.sin_addr.s_addr = INADDR_ANY;

    bzero(&(myaddr.sin_zero), 0);
    if(bind(listenfd, (struct sockaddr*)&myaddr, sizeof(struct sockaddr)) == -1){
        perror("bind: ");
        return -2;
    }
    printf("bind ok!\n");

    if(listen(listenfd, lisnum) == -1){
        perror("listen: ");
        return -3;
    }
    printf("listen ok!\n");

    char recvMsg[1024];
    sin_size = sizeof(myaddr);
    acceptfd = accept(listenfd, (struct sockaddr*)&myaddr, &sin_size);
    if(acceptfd < 0){
        close(listenfd);
        printf("accept failed!\n");
        return -4;
    }

    ssize_t readLen = MyRecv(acceptfd, recvMsg, sizeof(int));
    if(readLen < 0){
        printf("read failed!\n");
        return -5;
    }

    int len = (int)ntohl(*(int*)recvMsg);
    printf("len: %d\n", len);
    readLen = MyRecv(acceptfd, recvMsg, len);
    if(readLen < 0){
        printf("read failed!\n");
        return -6;
    }
    
    char* pBuff = recvMsg;
    int iLen = 0;
    Pkg RecvPkg;
    memcpy(&RecvPkg.head.num, pBuff + iLen, sizeof(int));
    iLen += sizeof(int);
    RecvPkg.head.num = ntohl(RecvPkg.head.num);
    printf("RecvPkg.head.num: %d\n",RecvPkg.head.num);

    memcpy(&RecvPkg.head.index, pBuff + iLen, sizeof(int));
    iLen += sizeof(int);
    RecvPkg.head.index = ntohl(RecvPkg.head.index);
    printf("RecvPkg.head.index: %d\n",RecvPkg.head.index);

    memcpy(&RecvPkg.content.sex, pBuff + iLen, sizeof(char));
    iLen += sizeof(char);
    printf("RecvPkg.content.sex: %c\n",RecvPkg.content.sex);

    memcpy(&RecvPkg.content.score, pBuff + iLen, sizeof(int));
    iLen += sizeof(int);
    RecvPkg.content.score = ntohl(RecvPkg.content.score);
    printf("RecvPkg.content.score: %d\n",RecvPkg.content.score);

    memcpy(&RecvPkg.content.address, pBuff + iLen, sizeof(RecvPkg.content.address));
    iLen += sizeof(RecvPkg.content.address);
    printf("RecvPkg.content.address: %s\n",RecvPkg.content.address);

    memcpy(&RecvPkg.content.age, pBuff + iLen, sizeof(int));
    iLen += sizeof(int);
    RecvPkg.content.age = ntohl(RecvPkg.content.age);
    printf("RecvPkg.content.age: %d\n",RecvPkg.content.age);

    close(acceptfd);
    close(listenfd);

    return 0;
}

